App = {
  web3Provider: null,
  contracts: {},

  init: function() {
    return App.initWeb3();
  },

  initWeb3: function() {
    // Initialize web3 and set the provider to the testRPC.
    if (typeof web3 !== 'undefined') {
      App.web3Provider = web3.currentProvider;
      web3 = new Web3(web3.currentProvider);
      console.info("if"+web3.currentProvider);
    } else {
      //truffle的私有链
      App.web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:9545');
      web3 = new Web3(App.web3Provider);
      console.info("else"+JSON.stringify(web3.currentProvider));
    }

    return App.initContract();
  },

  initContract: function() {

    //用来实例化智能合约，和智能合约是同名的:
    $.getJSON('TutorialToken.json', function(data) {

      //TutorialToken 就是abi
      var TutorialTokenArtifact = data;

      //创建TruffleContract对象
      App.contracts.TutorialToken = TruffleContract(TutorialTokenArtifact);

      //设置私有链
      App.contracts.TutorialToken.setProvider(App.web3Provider);

      //显示账户的余额:
      return App.getBalances();
    });

    return App.bindEvents();
  },

   //注册和绑定事件
  bindEvents: function() {
    $(document).on('click', '#transferButton', App.handleTransfer);
  },
    //当点击转账按钮后:
  handleTransfer: function(event) {
    event.preventDefault();
    //获得目标地址和要转账的金额:
    var amount = parseInt($('#TTTransferAmount').val());
    var toAddress = $('#TTTransferAddress').val();

    console.log('Transfer ' + amount + ' TT to ' + toAddress);
    //用来存储转账的智能合约:
    var tutorialTokenInstance;
    //web3.eth.getAccounts 可以是异步的，也可以是同步的:
    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }
      //默认获取第一个账户，也就是缺省的账户
      var account = accounts[0];
      //通过制定的合约名称来创建合约对象:
      App.contracts.TutorialToken.deployed().then(function(instance) {
        //将合约对象存储到实例中
        tutorialTokenInstance = instance;
        //调用智能合约的transfer, 此方法在父类:StandardToken已经定义了：
        return tutorialTokenInstance.transfer(toAddress, amount, {from: account, gas: 100000});
      }).then(function(result) {
        alert('Transfer Successful!');
        return App.getBalances();
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  },

  getBalances: function() {
    console.log('Getting balances...');

    var tutorialTokenInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }
      //默认第一个账户:
      var account = accounts[0];
      //实例化合约：
      App.contracts.TutorialToken.deployed().then(function(instance) {
        tutorialTokenInstance = instance;
        //调用合约返回当前账户的余额:
        return tutorialTokenInstance.balanceOf(account);
      }).then(function(result) {
          console.info(result);
        balance = result.c[0];


        $('#TTBalance').text(balance);
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  }

};

$(function() {
  $(window).load(function() {
    App.init();
  });
});
